package com.darin.camera;

import java.lang.reflect.Method;
import java.math.BigDecimal;

import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Point;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;

public class CommonUtil {
	private static final String TAG = "CommonUtil";

	public static boolean isPad(Context context) {
		Configuration config = context.getResources().getConfiguration();
		if ((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {
			Log.i(TAG, "screenLaytout : SCREENLAYOUT_SIZE_NORMAL");
			return false;
		} else if ((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4) {
			// Configuration.SCREENLAYOUT_SIZE_XLARGE in API 11
			Log.i(TAG, "screenLaytout : SCREENLAYOUT_SIZE_XLARGE");
			return true;
		} else {
			Log.i(TAG, "screenLaytout :" + (config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK));
			return false;
		}
	}

	public static boolean isRatio(int screenWidth, int screenHeight, int pvWidth, int pvHeight) {
		boolean result = false;
		BigDecimal bdsw = new BigDecimal(screenWidth);
		BigDecimal bdsh = new BigDecimal(screenHeight);
		BigDecimal sfRatio = bdsw.divide(bdsh, 2, BigDecimal.ROUND_HALF_DOWN);
		// Log.v(TAG, "sfRatio>>" + sfRatio.floatValue());

		BigDecimal bdpvw = new BigDecimal(pvWidth);
		BigDecimal bdpvh = new BigDecimal(pvHeight);
		BigDecimal pvRatio = bdpvw.divide(bdpvh, 2, BigDecimal.ROUND_HALF_DOWN);
		// Log.v(TAG, "pvRatio>>" + pvRatio.floatValue());
		if (pvRatio.doubleValue() == sfRatio.doubleValue()) {
			result = true;
		}
		return result;
	}

	public static Point getScreenResolution(WindowManager wm) {
		Display display = wm.getDefaultDisplay();
		Point size = new Point();
		
		try {
			display.getSize(size);
			if (android.os.Build.VERSION.SDK_INT < 13) {
				return size;
			} else if (android.os.Build.VERSION.SDK_INT == 13) {

				Method mrh = display.getClass().getMethod("getRealHeight");
				size.y = (Integer) mrh.invoke(display);
				Method mrw = display.getClass().getMethod("getRealWidth");
				size.x = (Integer) mrw.invoke(display);

			} else if (android.os.Build.VERSION.SDK_INT > 13&&android.os.Build.VERSION.SDK_INT<17) {

				Method mrh = display.getClass().getMethod("getRawHeight");
				size.y = (Integer) mrh.invoke(display);
				Method mrw = display.getClass().getMethod("getRawWidth");
				size.x = (Integer) mrw.invoke(display);

			}else if(android.os.Build.VERSION.SDK_INT>=17){
				Method mrh = display.getClass().getMethod("getRealSize",Point.class);
				mrh.invoke(display,size);
			}
		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			if (size.x <= 0 && size.y <= 0) {
				DisplayMetrics dm = new DisplayMetrics();
				display.getMetrics(dm);
				size.x = dm.widthPixels;
				size.y = dm.heightPixels;
			}
			Log.i(TAG,"getScreenResolution>>>"+size);
			return size;
		}
	}
}
